<?php


namespace app\model;

use think\facade\Db;
use think\Model;
use app\model\Attachment as AttachmentModel;
use app\model\QuotationTransportModel;
use app\model\QuotationModel;
use app\model\RemarkModel;
use app\model\CarModel;
use app\model\RouteModel;
use app\model\AddressModel;
use app\model\DeliveryAttachModel;
use app\model\DeliveryStepModel;
use app\model\ClearanceModel;

class DeliveryModel extends Model
{
    protected $table = "store_delivery";

    //添加
    public function add($data)
    {
        Db::startTrans();
        try {
            $param = $data;
            unset($param['goods_list']);
            unset($param['remark']);
            unset($param['token']);
            $param['create_at'] = date('Y-m-d H:i:s');
            $param['order_no'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $insertGetId = self::insertGetId($param);

            $goods_list_model = new AttachmentModel();
            $goods_list_str = '';
            if ($data['goods_list']) {
                $goods_list_arr = explode(',', $data['goods_list']);
                foreach ($goods_list_arr as $k => &$v) {
                    $goods_list_str .= $goods_list_model->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                }
                $goods_list_str = trim($goods_list_str, ',');
            }

            $RemarkModel = new RemarkModel();
            $remark_id = 0;
            if (!empty($data['remark'])) {
                $remark_id = $RemarkModel::remark_id($data['remark'], $this->table, $insertGetId);
            }

            self::where(["id" => $insertGetId])->update(['goods_list_id' => $goods_list_str, 'remark_id' => $remark_id]);

            /** *设置路线* **/
            $this->delivery_route($param, $insertGetId);

            /** *附属表插值* **/
            $DeliveryAttachModel = new DeliveryAttachModel();
            $DeliveryAttachModel->add($insertGetId);

            Db::commit();
            return self::find([$insertGetId]);
        } catch (\Exception $e) {
            Db::rollback();
            return '';
        }
    }

    /**
     * @param $param
     * @param $insertGetId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 设置路线
     * @author: dongdong
     * @date: 2025/1/2 16:22
     */
    public function delivery_route($param, $insertGetId, $flag = 0)
    {
        Db::startTrans();
        try {
            $departure_id = $param['departure_id'] ?? 0;
            $reach_id = $param['reach_id'] ?? 0;
            $transfer_id = $param['transfer_id'] ?? '';
            $port_service = $param['port_service'] ?? '';

            $RouteModel = new RouteModel();
            $AddressModel = new AddressModel();

            $data_arr = [];

            if ($param['delivery_type'] == 0) {

                $arr = $this->port_service_arr([], $port_service) ?? []; //服务数组

                $data_arr = $this->departure_arr($data_arr, $insertGetId, $departure_id, $flag); //出发数组

                foreach ($arr as $k => &$v) {
                    $area = Db::connect('fast_mysql')->table('fa_area')->field("id,pid,country")->where(["id" => $v['area_id']])->find();
                    $dd = [];
                    $dd['delivery_id'] = $insertGetId;
                    $dd['address_id'] = '';
                    $dd['address_type'] = 'transfer';
                    $dd['area_id'] = $v['area_id'];
                    if ($area) {
                        $dd['province_id'] = $area['pid'];
                        $dd['country'] = $area['country'];
                    } else {
                        $dd['province_id'] = '';
                        $dd['country'] = 0;
                    }
                    $dd['flag'] = $flag;
                    $dd['port_service'] = $v['demand'];
                    array_push($data_arr, $dd);
                }

                $data_arr = $this->reach_arr($data_arr, $insertGetId, $reach_id, $flag); //目的数组

                $RouteModel->insertAll($data_arr);

            } else {

                $arr = $this->port_service_arr([], $port_service); //服务数组

                $data_arr = $this->departure_arr($data_arr, $insertGetId, $departure_id, $flag); //出发数组

                $transfer_ddd = [];
                if (!empty($transfer_id)) {
                    $transfer_arr = explode(',', $transfer_id);
                    foreach ($transfer_arr as $k => &$v) {
                        array_push($transfer_ddd, $v);
                    }
                }

                foreach ($transfer_ddd as $k => &$v) {
                    $dd = [];
                    $dd['delivery_id'] = $insertGetId;
                    $dd['address_id'] = $v;
                    $dd['address_type'] = 'transfer';
                    $dd['area_id'] = $AddressModel->search_field_value(['id' => $v], 'area_id');
                    $area = Db::connect('fast_mysql')->table('fa_area')->field("id,pid,country")->where(["id" => $dd['area_id']])->find();
                    if ($area) {
                        $dd['province_id'] = $area['pid'];
                        $dd['country'] = $area['country'];
                    } else {
                        $dd['province_id'] = '';
                        $dd['country'] = '0';
                    }
                    $dd['flag'] = $flag;
                    $dd['port_service'] = '';
                    array_push($data_arr, $dd);
                }

                $data_arr = $this->reach_arr($data_arr, $insertGetId, $reach_id, $flag); //目的数组

                $RouteModel->insertAll($data_arr);

                //            foreach ($arr as $k => &$v) {
                //                $select = $RouteModel->where(['area_id' => $v['area_id'], 'delivery_id' => $insertGetId])->select();
                //                foreach ($select as $kk => &$vv) {
                //                    $str = '';
                //                    if (!in_array($v['demand'], explode(',', $vv['port_service']))) {
                //                        $str = $vv['port_service'] . ',' . $v['demand'];
                //                    }
                //                    $str = trim($str, ',');
                //                    $RouteModel->where(['area_id' => $v['area_id'], 'delivery_id' => $insertGetId])->update(['port_service' => $str]);
                //                }
                //            }

                $select = $RouteModel->where(['delivery_id' => $insertGetId])->select();
                foreach ($select as $k => &$v) {
                    if (!empty($arr[$k])) {
                        if ($arr[$k]['area_id'] == $v['area_id']) {
                            $RouteModel->where(['id' => $v['id']])->update(['port_service' => $arr[$k]['demand']]);
                        }
                    }
                }
            }

            Db::commit();

            $departure_transfer_reach = '';
            $store_route = $RouteModel->where(['delivery_id' => $insertGetId])->field("delivery_id,address_type,area_id")->select();
            foreach ($store_route as $k => &$v) {
                $departure_transfer_reach .= $v['address_type'] . ':' . $v['area_id'] . ',';
            }
            $departure_transfer_reach = trim($departure_transfer_reach, ',');
            self::where(['id' => $insertGetId])->update(['departure_transfer_reach' => $departure_transfer_reach]);

            return 1;
        } catch (\Exception $e) {
            Db::rollback();
            return 0;
        }
    }


    /**
     * @param array $arr
     * @param string $port_service
     * @return array
     * @notes 服务数组
     * @author: dongdong
     * @date: 2025/1/3 9:17
     */
    public function port_service_arr($arr = [], $port_service = "")
    {
        if (!empty($port_service)) {
            $port_service_arr = explode(';', $port_service) ?? [];
            foreach ($port_service_arr as $key => &$val) {
                $val_arr = explode(',', $val);
                $v_arr0 = explode(':', $val_arr[0]);
                $v_arr1 = explode(':', $val_arr[1]);
                array_push($arr, ['demand' => $v_arr0[1], 'area_id' => $v_arr1[1]]);
            }
        }
        return $arr;
    }

    /**
     * @param $data_arr
     * @param $insertGetId
     * @param $departure_id
     * @return mixed
     * @notes 出发数组录入
     * @author: dongdong
     * @date: 2025/1/3 10:04
     */
    public function departure_arr($data_arr, $insertGetId, $departure_id, $flag = 0)
    {
        $AddressModel = new AddressModel();
        $d['delivery_id'] = $insertGetId ?? 0;
        $d['address_id'] = $departure_id;
        $d['address_type'] = 'departure';
        $d['area_id'] = $AddressModel->search_field_value(['id' => $departure_id], 'area_id');
        $area = Db::connect('fast_mysql')->table('fa_area')->field("id,pid,country")->where(["id" => $d['area_id']])->find();
        if ($area) {
            $d['province_id'] = $area['pid'];
            $d['country'] = $area['country'];
        } else {
            $d['province_id'] = '';
            $d['country'] = '0';
        }
        $d['flag'] = $flag;
        $d['port_service'] = '';
        array_push($data_arr, $d);
        return $data_arr;
    }

    /**
     * @param $data_arr
     * @param $insertGetId
     * @param $reach_id
     * @return mixed
     * @notes 到达数组录入
     * @author: dongdong
     * @date: 2025/1/3 10:05
     */
    public function reach_arr($data_arr, $insertGetId, $reach_id, $flag = 0)
    {
        $AddressModel = new AddressModel();
        $d = [];
        $d['delivery_id'] = $insertGetId ?? 0;
        $d['address_id'] = $reach_id;
        $d['address_type'] = 'reach';
        $d['area_id'] = $AddressModel->search_field_value(['id' => $reach_id], 'area_id');
        $area = Db::connect('fast_mysql')->table('fa_area')->field("id,pid,country")->where(["id" => $d['area_id']])->find();
        if ($area) {
            $d['province_id'] = $area['pid'];
            $d['country'] = $area['country'];
        } else {
            $d['province_id'] = '';
            $d['country'] = '0';
        }
        $d['flag'] = $flag;
        $d['port_service'] = '';
        array_push($data_arr, $d);
        return $data_arr;
    }

    /**
     * @param $insertGetId
     * @param int $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 路线呈现
     * @author: dongdong
     * @date: 2025/1/3 15:22
     */
    public function route_list($insertGetId, $type = 0)
    {
        $RouteModel = new RouteModel();
        $AddressModel = new AddressModel();
        $arr = [];

        $route_list = $RouteModel->where(["delivery_id" => $insertGetId])->select();
        $route_echo = [];
        $count = count($route_list) - 1;
        $flag = 0;
        $row = $RouteModel->where(["delivery_id" => $insertGetId])->where(['address_type' => 'departure'])->order("id asc")->limit(1)->find();
        if ($row) {
            foreach ($route_list as $k => &$v) {
                if (($k == 0) && ($v['address_type'] == 'departure')) {
                    array_push($route_echo, $v);
                    $find = $RouteModel->where(["delivery_id" => $insertGetId])->where(['address_type' => 'transfer'])->order("id asc")->limit(1)->find();
                    if ($find) {
                        if ($find['area_id'] == $v['area_id']) {
                            $flag = 1;
                            $explode_ar = explode(',', $route_echo[0]['port_service']);
                            if (!in_array($find['port_service'], $explode_ar)) {
                                $route_echo[0]['port_service'] = trim($route_echo[0]['port_service'] . ',' . $find['port_service'], ',');
                            }
                        }
                    }
                }

                if (($k == 1) && ($v['address_type'] != 'reach')) {
                    if ($row) {
                        if ($flag == 1) {
                            $v['status'] = 0;
                        }
                    }
                    array_push($route_echo, $v);
                }
                if (($k > 1) && ($k < $count) && ($v['address_type'] != 'reach')) {
                    array_push($route_echo, $v);
                }

                if (($k == $count) && ($v['address_type'] == 'reach')) {
                    array_push($route_echo, $v);
                    if (!empty($route_echo[$count - 1])) {
                        $echo = $route_echo[$count - 1];
                        if ($echo['address_type'] != 'departure') {
                            if ($echo['area_id'] == $route_echo[$k]['area_id']) {
                                $explode_arr = explode(',', $route_echo[$k]['port_service']);
                                if (!in_array($echo['port_service'], $explode_arr)) {
                                    $route_echo[$k]['port_service'] = trim($route_echo[$k]['port_service'] . ',' . $echo['port_service'], ',');
                                }
                                $route_echo[$count - 1]['status'] = 0;
                            }
                        }
                    }
                }
            }

            foreach ($route_echo as $k => &$v) {
                if ($v['status'] == 1) {
                    $v['area'] = $AddressModel->area_arr($v);
                    $v['address'] = $AddressModel->info($v);
                    array_push($arr, $v);
                }
            }

            if ($type == 0) {
                return $arr;
            } else {
                _d($arr);
            }

        } else {
            $route_echo = $RouteModel->where(["delivery_id" => $insertGetId])->where(['address_type' => 'transfer'])->order("id asc")->select();
            foreach ($route_echo as $k => &$v) {
                if ($v['status'] == 1) {
                    $v['area'] = $AddressModel->area_arr($v);
                    $v['address'] = $AddressModel->info($v);
                    array_push($arr, $v);
                }
            }
            if ($type == 0) {
                return $arr;
            } else {
                _d($arr);
            }
        }
    }


    /**
     * @param $param
     * @return DeliveryModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 发货记录
     * @author: dongdong
     * @date: 2025/1/8 11:59
     */
    public function delivery_record($param)
    {
        $page = $param['page'] ?? 1;
        $status = $param['status'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $page = ($page - 1) * $limit;
        $user_id = $param['user_id'];
        $where['is_deleted'] = 0;
        if ($status) {
            $where['status'] = $status;
        }

        return $this->record_handle(self::where(['user_id' => $user_id])->where($where)->order("id desc")->limit($page, $limit)->select(), $user_id);
    }

    /**
     * @param $list
     * @param int $user_id
     * @return array
     * @notes 记录处理
     * @author: dongdong
     * @date: 2025/2/26 16:16
     */
    public function record_handle($list, $user_id = 0)
    {
        $arr = [];
        $AddressModel = new AddressModel();
        $GoodsModel = new GoodsModel();
        $SizeModel = new SizeModel();
        $VehicleModel = new VehicleModel();
        $ConfigModel = new ConfigModel();
        $RemarkModel = new RemarkModel();
        $Attachment = new AttachmentModel();
        $DeliveryAttachModel = new DeliveryAttachModel();
        $ClearanceModel = new ClearanceModel();

        try {
            foreach ($list as $k => &$v) {
                $v['user'] = Db::connect("fast_mysql")->table("fa_user")->where(["id" => $v['user_id']])->field("username,username_ru,mobile,level,avatar")->find();
                $v['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v['user_id']])->field("identity_id,country,profile,profile_ru")->find();

                $v['departure'] = $AddressModel->address_content($v['departure_id']);
                $v['reach'] = $AddressModel->address_content($v['reach_id']);
                $transfer_route = $this->route_list($v['id'], $type = 0);
                $v['transfer_count'] = 0;
                foreach ($transfer_route as $kk => &$vv) {
                    if ($vv['address_type'] == 'transfer') {
                        $v['transfer_count'] += 1;
                    }
                }
                $v['attachment_info'] = $Attachment->info($this->table, $v['id']);
                $v['remark_info'] = $RemarkModel->info($v['remark_id']);
                $v['size_info'] = $SizeModel->info($v['size_id']);
                $v['vehicle_info'] = $VehicleModel->info($v['vehicle_id']);
                $v['railway_wagon_info'] = $ConfigModel->info($v['railway_wagon']);
                $v['goods_info'] = $GoodsModel->info($v['goods_id']);
                if ($v['port_service']) {
                    $v['demand_area'] = $this->demand_area($v['port_service']);
                } else {
                    $v['demand_area'] = [];
                }
                $v['attach'] = $DeliveryAttachModel->where(["delivery_id" => $v['id']])->find();
                $v['after_sale'] = Db::table("store_after_sales")->where(["delivery_id" => $v['id']])->select();
                $v['cooperate'] = Db::connect("fast_mysql")->table("fa_user")->where(["id" => $v['attach']['cooperate_user_id']])->field("id,username,username_ru,mobile,level,avatar")->find();
                $delivery_id = $v['id'];
                $quotation = Db::table("store_quotation")->where(['delivery_id' => $delivery_id, 'user_id' => $user_id])->where(['is_deleted' => 0])->field("id")->find();
                $quotation_transport = Db::table("store_quotation_transport")->where(['delivery_id' => $delivery_id, 'user_id' => $user_id])->where(['is_deleted' => 0])->field("id")->find();

                $v['is_quotation'] = 0;
                if (($quotation) || ($quotation_transport)) {
                    $v['is_quotation'] = 1;
                }

                $v['quotation_info'] = [];
                if ($v['demand'] == 1) {
                    if ($v['attach']) {
                        if ($v['attach']['cooperate_id']) {
                            $quotation_arr = [];
                            $quotation_info = Db::table("store_quotation_transport")->where('id', "in", $v['attach']['cooperate_id'])->select();
                            foreach ($quotation_info as $k2 => &$v2) {
                                $v2['user'] = Db::connect("fast_mysql")->table("fa_user")->where(["id" => $v2['user_id']])->field("username,username_ru,mobile,level,avatar")->find();
                                $v2['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v2['user_id']])->field("identity_id,country,profile,profile_ru")->find();
                                $v2['car'] = Db::table("store_car")->where(['id' => $v2['car_id']])->find();
                                array_push($quotation_arr, $v2);
                            }
                            $v['quotation_info'] = $quotation_arr;
                        }
                    }
                } else {
                    if ($v['attach']) {
                        if ($v['attach']['cooperate_id']) {
                            $quotation_arr = [];
                            $quotation_info = Db::table("store_quotation")->where('id', "in", $v['attach']['cooperate_id'])->select();
                            foreach ($quotation_info as $k3 => &$v3) {
                                $v3['user'] = Db::connect("fast_mysql")->table("fa_user")->where(["id" => $v3['user_id']])->field("username,username_ru,mobile,level,avatar")->find();
                                $v3['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v3['user_id']])->field("identity_id,country,profile,profile_ru")->find();
                                $v3['remark'] = $RemarkModel->find($v3['remark_id']);
                                $v3['transport_remark'] = $RemarkModel->find($v3['transport_remark_id']);
                                $v3['attachment'] = $Attachment->lists("store_quotation", $v3['attachment_id']);
                                $v3['transport_attachment'] = $Attachment->lists("store_quotation", $v3['transport_attachment_id']);
                                array_push($quotation_arr, $v3);
                            }
                            $v['quotation_info'] = $quotation_arr;
                        }
                    }
                }

                $v['clearance_find'] = $ClearanceModel->info($v['clearance_id']);
                array_push($arr, $v);
            }
            return $arr;
        } catch (\Exception $e) {
            _d($e);
            return [];
        }
    }


    /**
     * @param $demand_area
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 需求城市处理
     * @author: dongdong
     * @date: 2025/1/8 16:09
     */
    public function demand_area($demand_area)
    {
        $AddressModel = new AddressModel();
        $array = [];
        $arr = explode(';', $demand_area);
        foreach ($arr as $k => &$v) {
            $arr1 = explode(',', $v);

            $arr2 = explode(':', $arr1[0]);
            $demand = $arr2[1];

            $arr3 = explode(':', $arr1[1]);
            $area_id = $arr3[1];
            array_push($array, ['demand' => $demand, 'area_id' => $area_id]);
        }

        foreach ($array as $k => &$v) {
            $v['area_info'] = $AddressModel->area_short($v);
        }

        return $array;
    }


    /**
     * @param $param
     * @return int|string
     * @notes 取消发布
     * @author: dongdong
     * @date: 2025/1/11 14:21
     */
    public function cancel_delivery($param)
    {
        try {
            self::where(['id' => $param['delivery_id'], 'user_id' => $param['user_id']])->update(['is_deleted' => 1, 'delete_time' => date('Y-m-d H:i:s')]);
            return 1;
        } catch (\Exception $e) {
            return '';
        }
    }

    /**
     * @param $param
     * @return int|string
     * @notes 确认报价 发货
     * @author: dongdong
     * @date: 2025/1/11 15:03
     */
    public function send_delivery($param)
    {
        Db::startTrans();
        try {
            $delivery_record = self::where(['id' => $param['delivery_id'], 'user_id' => $param['user_id'], 'status' => 1])->find();
            if (empty($delivery_record)) {
                Db::commit();
                return '报价记录未找到';
            }
            if ($param['is_transport'] == 1) {
                $bool = true;
                $quota = explode(',', $param['quota_id']);
                $user_arr = [];
                $cooperate_user_id = '';
                $QuotationTransportModel = new QuotationTransportModel();
                $DeliveryAttachModel = new DeliveryAttachModel();

                foreach ($quota as $k => &$v) {
                    $find = $QuotationTransportModel->where(['delivery_id' => $param['delivery_id']])->where(['id' => $v])->find();
                    if (empty($find)) {
                        $bool = false;
                    } else {
                        $car_id = $find['car_id'];
                        Db::table("store_car")->where("id=$car_id")->update(['order_id' => $param['delivery_id'], 'status' => 3, 'send_jb_time' => time()]);
                        $user_id = $find['user_id'];
                        //if (!in_array($user_id, $user_arr)) {
                        array_push($user_arr, $user_id);
                        //}
                        if ($user_arr) {
                            $cooperate_user_id = implode(',', $user_arr);
                        }
                    }
                }

                if ($bool) {
                    $date = date('Y-m-d H:i:s');
                    if (count($user_arr) <= 1) {
                        self::where(['id' => $param['delivery_id'], 'user_id' => $param['user_id']])->update(['status' => 2, 'is_deleted' => 0]);
                        $DeliveryAttachModel->where(['delivery_id' => $param['delivery_id']])->update(['cooperate_at' => $date, 'cooperate_id' => $param['quota_id'], 'cooperate_user_id' => $cooperate_user_id, 'is_transport' => $param['is_transport']]);
                    } else {
                        $DeliveryAttachModel->where(['delivery_id' => $param['delivery_id']])->update(['cooperate_at' => $date, 'cooperate_id' => $param['quota_id'], 'cooperate_user_id' => $cooperate_user_id, 'is_transport' => $param['is_transport']]);
                        self::where(['id' => $param['delivery_id'], 'user_id' => $param['user_id']])->update(['status' => 2, 'is_deleted' => 1]);

                        foreach ($quota as $kk => &$vv) {
                            $d['parent_id'] = $delivery_record['id'];
                            $d['user_id'] = $delivery_record['user_id'];
                            $d['demand'] = $delivery_record['demand'];
                            $d['departure_id'] = $delivery_record['departure_id'];
                            $d['transfer_id'] = $delivery_record['transfer_id'];
                            $d['reach_id'] = $delivery_record['reach_id'];
                            $d['create_at'] = $date;
                            $d['goods_id'] = $delivery_record['goods_id'];
                            $d['goods_list_id'] = $delivery_record['goods_list_id'];
                            $d['transport_type'] = $delivery_record['transport_type'];
                            $d['transport_way'] = $delivery_record['transport_way'];
                            $d['size_id'] = $delivery_record['size_id'];
                            $d['vehicle_id'] = $delivery_record['vehicle_id'];
                            $d['railway_wagon'] = $delivery_record['railway_wagon'];
                            $d['goods_num'] = $delivery_record['goods_num'];
                            $d['delivery_at'] = $delivery_record['delivery_at'];
                            $d['tel'] = $delivery_record['tel'];
                            $d['remark_id'] = $delivery_record['remark_id'];
                            $d['port_service'] = $delivery_record['port_service'];
                            $d['price'] = $delivery_record['price'];
                            $d['price_unit'] = $delivery_record['price_unit'];
                            $d['lang'] = $delivery_record['lang'];
                            $d['version'] = $delivery_record['version'];
                            $d['goods_type'] = $delivery_record['goods_type'];
                            $d['delivery_type'] = $delivery_record['delivery_type'];
                            $d['release_type'] = $delivery_record['release_type'];
                            $d['release_user_id'] = $delivery_record['release_user_id'];
                            $d['order_no'] = $delivery_record['order_no'] . $kk;
                            $d['related_orders'] = $delivery_record['related_orders'];
                            $d['status'] = 2;
                            $d['departure_transfer_reach'] = $delivery_record['departure_transfer_reach'];
                            $d['load_num'] = $delivery_record['load_num'];
                            $d['unload_num'] = $delivery_record['unload_num'];
                            $d['clearance_id'] = $delivery_record['clearance_id'];
                            $d['is_load'] = $delivery_record['is_load'];
                            $d['is_stock'] = $delivery_record['is_stock'];

                            $insert_id = self::insertGetId($d);

                            $da['delivery_id'] = $insert_id;
                            $da['cooperate_id'] = $vv;
                            $da['cooperate_at'] = $date;
                            $da['cooperate_user_id'] = $user_arr[$kk];
                            $DeliveryAttachModel->insert($da);
                        }
                    }

                    Db::commit();
                    return 1;
                } else {
                    Db::commit();
                    return '暂未找到报价记录';
                }

            } else {

                self::where(['id' => $param['delivery_id'], 'user_id' => $param['user_id']])->update(['status' => 2]);

                $QuotationModel = new QuotationModel();
                $find = $QuotationModel->where(['delivery_id' => $param['delivery_id']])->where(['id' => $param['quota_id']])->find();
                if ($find) {
                    $cooperate_user_id = $find['user_id'];
                    self::where(['id' => $param['delivery_id'], 'user_id' => $param['user_id']])->update(['status' => 2]);
                    $DeliveryAttachModel = new DeliveryAttachModel();
                    $DeliveryAttachModel->where(['delivery_id' => $param['delivery_id']])->update(['cooperate_at' => date('Y-m-d H:i:s'), 'cooperate_id' => $param['quota_id'], 'cooperate_user_id' => $cooperate_user_id, 'is_transport' => $param['is_transport']]);
                    Db::commit();
                    return 1;
                } else {
                    Db::commit();
                    return '未找到报价记录';
                }
            }
        } catch (\Exception $e) {
            _d($e);
            Db::rollback();
            return '请求失败';
        }
    }

    /**
     * @param $param
     * @return DeliveryStepModel[]|array|\think\Collection
     * @notes 订单步骤
     * @author: dongdong
     * @date: 2025/1/11 17:43
     */
    public function delivery_step($param)
    {
        try {
            $DeliveryStepModel = new DeliveryStepModel();
            return $DeliveryStepModel->info($param['delivery_id']) ?? [];
        } catch (\Exception $e) {
            return [];
        }
    }


    /**
     * @param $param
     * @return array
     * @notes 货源信息
     * @author: dongdong
     * @date: 2025/1/13 17:51
     */
    public function delivery_select($param)
    {
        try {
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            $page = ($page - 1) * $limit;
            $user_id = $param['user_id'];

            $search_time = $param['search_time'] ?? 0;
            $start_time = $param['start_time'] ?? '';
            $end_time = $param['end_time'] ?? '';

//            $departure_area = $param['departure_area'] ?? '';
//            $reach_area = $param['reach_area'] ?? '';

            $departure_str = $param['departure_area'] ?? '';
            $reach_str = $param['reach_area'] ?? '';

            $keyword = $param['keyword'] ?? '';
            $demand = $param['demand'] ?? '';

            $transport_type = $param['transport_type'] ?? '';
            $transport_way = $param['transport_way'] ?? '';
            $size_id = $param['size_id'] ?? '';
            $vehicle_id = $param['vehicle_id'] ?? '';

            $goods_type = $param['goods_type'] ?? 0;
            if (empty($param['release_type'])) {
                $param['release_type'] = 0;
            }

            $order = "d.id desc";

            $where = "";
            if (!empty($search_time)) {
                if ($search_time == 1) {
                    $start_time = date('Y-m-d') . ' ' . '00:00:00';
                    $end_time = date('Y-m-d', strtotime('+1 day')) . ' ' . '00:00:00';
                    $where .= " and d.create_at>='$start_time' and d.create_at<='$end_time'";
                }
                if ($search_time == 2) {
                    $start_time = date('Y-m-d', strtotime('-3 days')) . ' ' . '00:00:00';
                    $end_time = date('Y-m-d', strtotime('+1 day')) . ' ' . '00:00:00';
                    $where .= " and d.create_at>='$start_time' and d.create_at<='$end_time'";
                }
                if ($search_time == 3) {
                    $start_time = date('Y-m-d', strtotime('-7 days')) . ' ' . '00:00:00';
                    $end_time = date('Y-m-d', strtotime('+1 day')) . ' ' . '00:00:00';
                    $where .= " and d.create_at>='$start_time' and d.create_at<='$end_time'";
                }
            } else {
                if ($start_time) {
                    if ($end_time) {
                        $where .= " and d.create_at>='$start_time' and d.create_at<='$end_time'";
                    }
                }
            }


            if ($transport_type) {
                $where .= " and d.transport_type='$transport_type'";
            }
            if ($transport_way != '') {
                if ($transport_way == 0) {
                    $order = "d.transport_way asc,d.id desc";
                    $where .= " and d.transport_way='$transport_way'";
                } else {
                    $order = "d.transport_way asc,d.id desc";
                    $where .= " and d.transport_way='$transport_way'";
                }
            }


            if ($size_id) {
                $where .= " and d.size_id='$size_id'";
            }
            if ($vehicle_id) {
                $where .= " and d.vehicle_id='$vehicle_id'";
            }

            if ($goods_type == 0) {
                $where .= " and d.goods_type='$goods_type'";
            } elseif ($goods_type == 1) {
                $where .= " and d.goods_type='$goods_type'";

                $min_weight = $param['min_weight'] ?? '';
                $max_weight = $param['max_weight'] ?? '';
                $min_volume = $param['min_volume'] ?? '';
                $max_volume = $param['max_volume'] ?? '';

                if ($min_weight) {
                    $where .= " and g.goods_weight>='$min_weight'";
                    if ($max_weight) {
                        $where .= " and g.goods_weight>='$min_weight' and g.goods_weight<='$max_weight'";
                    }
                } else {
                    if ($max_weight) {
                        $where .= " and g.goods_weight<='$max_weight'";
                    }
                }

                if ($min_volume) {
                    $where .= " and g.goods_volume>='$min_volume'";
                    if ($max_volume) {
                        $where .= " and g.goods_volume>='$min_volume' and g.goods_volume<='$max_volume'";
                    }
                } else {
                    if ($max_volume) {
                        $where .= " and g.goods_volume<='$max_volume'";
                    }
                }

            }


            $w = "";
//            if ($departure_area) {
//                $departure_like = 'departure:' . $departure_area;
//                if ($reach_area) {
//                    $reach_like = 'reach:' . $reach_area;
//                    $w .= " and (d.departure_transfer_reach like '%$departure_like%' and  d.departure_transfer_reach like '%$reach_like%')";
//                } else {
//                    $w .= " and d.departure_transfer_reach like '%$departure_like%'";
//                }
//            } else {
//                if ($reach_area) {
//                    $reach_like = 'reach:' . $reach_area;
//                    $w .= " and d.departure_transfer_reach like '%$reach_like%'";
//                }
//            }


            $delivery_ids = '';
            if ($departure_str) {
                $dw = '';
                $departure_arr = explode(',', $departure_str);

                if ($departure_arr) {
                    $d_country = $departure_arr[0];
                    $d_province = $departure_arr[1];
                    $d_city = $departure_arr[2];
                    if ($d_city != '-1') {
                        $dw = "((address_type='departure' and area_id='{$d_city}') or (address_type='transfer' and area_id='{$d_city}'))";
                    } else {
                        if ($d_province != '-1') {
                            $dw = "((address_type='departure' and province_id='{$d_province}') or (address_type='transfer' and province_id='{$d_province}'))";
                        } else {
                            if($d_country !='-1'){
                                $dw = "((address_type = 'departure' AND country = '{$d_country}') OR (address_type = 'transfer' AND country = '{$d_country}'))";;
                            }
                        }
                    }


                }
                $search_route = Db::table("store_route")->where("flag",0)->whereRaw($dw)->group('delivery_id')->field("delivery_id")->select();
                if (count($search_route) > 0) {
                    foreach ($search_route as $k => &$v) {
                        $delivery_ids .= $v['delivery_id'] . ',';
                    }
                } else {
                    return [];
                    exit;
                }
            }
            if ($reach_str) {
                $rw = '';
                $reach_str = explode(',', $reach_str);
                if ($reach_str) {
                    $r_country = $reach_str[0];
                    $r_province = $reach_str[1];
                    $r_city = $reach_str[2];
                    if ($r_city != '-1') {
                        $rw = "((address_type='departure' and area_id='{$r_city}') or (address_type='transfer' and area_id='{$r_city}'))";
                    } else {
                        if ($r_province != '-1') {
                            $rw = "((address_type='departure' and province_id='{$r_province}') or (address_type='transfer' and province_id='{$r_province}'))";
                        } else {
                            if($r_country !='-1'){
                                $rw = "((address_type='departure' and country='{$r_country}') or (address_type='transfer' country='{$r_country}'))";
                            }
                        }
                    }
                }
                $search_route = Db::table("store_route")->where("flag=0")->whereRaw($rw)->field("delivery_id")->group("delivery_id")->select();
                if (count($search_route) > 0) {
                    foreach ($search_route as $k => &$v) {
                        $delivery_ids .= $v['delivery_id'] . ',';
                    }
                } else {
                    return [];
                    exit;
                }
            }


            if ($delivery_ids) {
                $delivery_ids = trim($delivery_ids, ',');
            }


            $wh = "";
            if ($keyword) {
                $wh .= " and (g.title like '%$keyword%' or g.title_ru like '%$keyword%')";
            }

            $whe = "";
            if ($demand) {
                $arr = explode(',', $demand);
                $ids = '';
                $ids_arr = [];
                foreach ($arr as $k => &$v) {
                    $search_demand = Db::table("store_route")->alias("r")->join("store_delivery d", "d.id=r.delivery_id")
                        ->where("r.port_service='$v'")->where("d.status=1")->field("r.delivery_id")->select();
                    foreach ($search_demand as $kk => &$vv) {
                        if (!in_array($vv['delivery_id'], $ids_arr)) {
                            array_push($ids_arr, $vv['delivery_id']);
                        }
                    }
                }
                if (count($ids_arr)) {
                    $ids = implode(',', $ids_arr);
                }
                if ($ids) {
                    if ($delivery_ids) {
                        $whe = " and d.id in ($ids) or d.id in ($delivery_ids)";
                    } else {
                        $whe = " and d.id in ($ids)";
                    }
                } else {
                    if ($delivery_ids) {
                        $whe = " and d.id in ($delivery_ids)";
                    }
                }
            } else {
                if ($delivery_ids) {
                    $whe = " and d.id in ($delivery_ids)";
                }
            }

            if ($param['release_type'] != 1) {
                $list = Db::query("select d.* from store_delivery d left join store_goods g on d.goods_id=g.id where d.status=1 and d.release_type='0' $where $w $wh $whe  order by $order limit $page,$limit");
            } else {
                $list = Db::query("select d.* from store_delivery d left join store_goods g on d.goods_id=g.id where d.status=1 and d.release_type='1' $where $w $wh $whe  and FIND_IN_SET($user_id,d.release_user_id) order by $order limit $page,$limit");
            }

            $list = $this->record_handle($list, $user_id);
            return $list;
        } catch (\Exception $e) {
            dd($e->getMessage());
            return [];
        }
    }


    /**
     * @param $param
     * @return CarModel[]|array|\think\Collection
     * @notes 车辆资源
     * @author: dongdong
     * @date: 2025/1/15 11:46
     */
    public function car_source($param)
    {
        try {
            $CarModel = new CarModel();
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            $page = ($page - 1) * $limit;

            $status = $param['status'] ?? '';
            $mode = $param['mode'] ?? '';
            $brand = $param['brand'] ?? '';
            $area_id = $param['area_id'] ?? '';
            $is_company = $param['is_company'] ?? '';
            $transport_list = $param['transport_list'] ?? '';

            $where = "is_deleted=0 and driver_id !=''";
            $car_category_id = "";

            if ($status) {
                $where .= " and status='$status'";
            }


            if ($brand) {
                $arr = explode(',', $brand);
                if (($arr) && (count($arr) > 1)) {
                    $mode = $arr[0];
                    $car_category_id = $arr[1];
                }
                if ($mode) {
                    $where .= " and mode='$mode'";
                }
                if ($car_category_id) {
                    $where .= " and car_category_id='$car_category_id'";
                }
            } elseif (!empty($mode)) {
                $where .= " and mode='$mode'";
            }


            if ($area_id) {
                if (is_numeric($area_id)) {
                    $where .= " and current_city_id='$area_id'";
                } else {
                    $city_arr = explode(',', $area_id);
                    if ($city_arr) {
                        $d_country = $city_arr[0];
                        $d_province = $city_arr[1];
                        $d_city = $city_arr[2];
                        if ($d_city != '-1') {
                            $where .= " and current_city_id='$d_city'";
                        } else {
                            if ($d_province != '-1') {
                                $where .= " and current_province_id='$d_province'";
                            } else {
                                $where .= " and current_country='$d_country'";
                            }
                        }
                    }
                }
            }


            if ($is_company) {
                $where .= " and is_company='$is_company'";
            }

            if ($transport_list!='-1,5055,5056,-1,5055,5056') {
                $where .= " and transport_list like '%$transport_list%'";
            }


            $list = $CarModel->where($where)->order("id desc")->limit($page, $limit)->select();

            $driverModel = new DriverModel();
            $arr = [];
            foreach ($list as $k => &$v) {
                $v['car_category_name'] = $CarModel->car_category_name($v['car_category_id']);
                $v['area'] = Db::connect('fast_mysql')->table('fa_area')->where(["id" => $v['current_city_id']])->find();

                $v['driver'] = $driverModel->where(["id" => $v['driver_id']])->find();
                if (empty($v['driver_id'])) {
                    $v['status'] = 4;
                }

                if (!empty($v['driver']['bind_user_id'])) {
                    $v['user'] = Db::connect("fast_mysql")->table("fa_user")->field("id,username,username_ru,mobile,level,avatar")->where(["id" => $v['driver']['bind_user_id']])->find();
                    $v['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v['driver']['bind_user_id']])->field("identity_id,country,profile,profile_ru")->find();
                } else {
                    $v['user'] = Db::connect("fast_mysql")->table("fa_user")->field("id,username,username_ru,mobile,level,avatar")->where(["id" => $v['user_id']])->find();
                    $v['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v['user_id']])->field("identity_id,country,profile,profile_ru")->find();
                }

                $v['order'] = self::where(['id' => $v['order_id']])->select();
                if ($v['order']) {
                    $v['order_delivery'] = $this->record_handle($v['order'], $param['user_id']);
                }
                $tt = [];
                $result = explode(';', $v['transport_list']);
                foreach ($result as $k6 => &$v6) {
                    $dd = explode(',', $v6);
                    array_push($tt, ['departure_city' => $this->city($dd[0]), 'reach_city' => $this->city($dd[1])]);
                }
                $v['transport_arr'] = $tt;
                array_push($arr, $v);
            }

//            var_dump($arr);die;
            foreach ($arr as $k => &$v) {
                $v['luxian'] = [];

                if ($v['cfd_transports'] && $v['mdd_transports']) {
                    $cfd_transports = explode(';', $v['cfd_transports']);
                    $mdd_transports = explode(';', $v['mdd_transports']);
                    $arrs = [];
                    foreach ($cfd_transports as $kk => $vv) {
                        if ($vv) {
                            $ar = explode(',', $vv);
                            if ($ar[2] == '-1' && $ar[1] == '-1') {
                                $cfd = areas()[$ar[0]];
                            } elseif ($ar[2] == '-1' && $ar[1] != '-1') {
                                $cfd = $this->citys($ar[1]);
                            } else {
                                $cfd = $this->citys($ar[2]);
                            }
                            $cfd['id'] = $vv;
                            $arrs[$kk]['cfd'] = $cfd;
                        }
                    }
                    foreach ($mdd_transports as $kk => $vv) {
                        if ($vv) {
                            $ar = explode(',', $vv);
                            if ($ar[2] == '-1' && $ar[1] == '-1') {
                                $mdd = areas()[$ar[0]];
                            } elseif ($ar[2] == '-1' && $ar[1] != '-1') {
                                $mdd = $this->citys($ar[1]);
                            } else {
                                $mdd = $this->citys($ar[2]);
                            }
                            $mdd['id'] = $vv;
                            $arrs[$kk]['mdd'] = $mdd;
                        }
                    }
                    $v['luxian'] = $arrs;
                }

            }

            return $arr;
        } catch (\Exception $e) {
            return [];
        }
    }

    public function areas()
    {
        $data = [
            [
                'shortname' => '中国',
                'shortname_ru' => 'Китай',
                'name' => '中国',
                'name_ru' => 'Китай',
                'mergename' => 'Китай',
                'mergename_ru' => 'Китай',
                'country' => 0
            ],
            [
                'shortname' => '俄罗斯',
                'shortname_ru' => 'Россия',
                'name' => '俄罗斯',
                'name_ru' => 'Россия',
                'mergename' => 'Россия',
                'mergename_ru' => 'Россия',
                'country' => 1
            ],
            [
                'shortname' => '哈萨克斯坦',
                'shortname_ru' => 'Казахстан',
                'name' => '哈萨克斯坦',
                'name_ru' => 'Казахстан',
                'mergename' => 'Казахстан',
                'mergename_ru' => 'Казахстан',
                'country' => 2
            ],
            [
                'shortname' => '白俄罗斯',
                'shortname_ru' => 'Беларусь',
                'name' => '白俄罗斯',
                'name_ru' => 'Беларусь',
                'mergename' => 'Беларусь',
                'mergename_ru' => 'Беларусь',
                'country' => 3
            ],
        ];
        return $data;
    }


    /**
     * @param $id
     * @return array|mixed|\think\db\BaseQuery|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 城市
     * @author: dongdong
     * @date: 2025/2/17 15:32
     */
    public function city($id)
    {
        if ($id != 'undefined') {
            return Db::connect('fast_mysql')->table("fa_area")->field("id,shortname,shortname_ru,name,name_ru,mergename,mergename_ru")->where("id=$id")->find();
        } else {
            return [];
        }
    }

    public function citys($id)
    {
        if ($id) {
            return Db::connect("fast_mysql")->table("fa_area")->field("shortname,shortname_ru,name,name_ru,mergename,mergename_ru,country")->where("id", "in", $id)->find();
        } else {
            return [];
        }
    }

}